package com.ruoyi.quartz.task;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.service.ChargeService;
import com.ruoyi.business.service.ITOrderInfoService;
import com.ruoyi.business.service.ITRecipientInfoService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HttpResponse;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Component
public class AliSybOrderCheckTask {


    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;

    private Log logger = Log.get();

    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    @Scheduled(fixedRate = 5000)
    public void checkOrder() throws Exception {
//        logger.info("SYB订单查询..");
        Calendar c = Calendar.getInstance();
        TOrderInfo orderquery = new TOrderInfo();
        orderquery.setChannelType("alipay");
        orderquery.setChannel("alipay_syb_h5");
        orderquery.setStatus(1);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoList(orderquery);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        Date startTime = DateUtils.getStartOfDay(new Date());
        Date endTime = DateUtils.getEndOfDay(new Date());
        String startTimeStr = sdf.format(startTime);
        String endTimeStr = sdf.format(endTime);
        for (TOrderInfo orderInfo : orderInfos) {
            if (StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                continue;
            }
            TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
            String url = "https://www.shouyinbei.net/api/merchantOrder/queryMerchantOrderList";
            String cookieStr = userRecipientInfo.getCookie();
            JSONObject cookieObj = JSONObject.parseObject(cookieStr);
            String merchantCode = cookieObj.getString("merchantCode");
            String token = cookieObj.getString("token");
            String userId = cookieObj.getString("userId");

            JSONObject queryObj = new JSONObject();
            queryObj.put("userId", userId);
            queryObj.put("cashPlaceId", "");

            queryObj.put("page", 1);
            queryObj.put("status", 1);
            queryObj.put("staffCode", "");

            queryObj.put("settlementType", "");

            queryObj.put("merchantCode", merchantCode);
            queryObj.put("size", 20);
            queryObj.put("startTime", startTimeStr);
            queryObj.put("storeId", "");
            queryObj.put("endTime", endTimeStr);
            queryObj.put("payTypeCode", "aliPay");

            HashMap<String, String> headerMap = new HashMap();
            headerMap.put("myLoginName", cookieObj.getString("loginName"));
            headerMap.put("token", token);
            logger.info(cookieObj.getString("loginName") + "  " + token + " SYB订单查询请求：" + queryObj.toJSONString());
            String httpResponse = HttpUtils.sendJsonMessage(url, headerMap, queryObj.toJSONString());
            JSONObject resultObj = JSONObject.parseObject(httpResponse);
//            logger.info("SYB订单查询.." + resultObj);

            int resultCode = resultObj.getInteger("code");
//            logger.info("SYB订单查询请求：" + queryObj.toJSONString());
            if (resultCode == 200) {
                JSONArray recordList = resultObj.getJSONObject("data").getJSONObject("pager").getJSONArray("data");
                for (int i = 0; i < recordList.size(); i++) {
                    JSONObject recordObj = recordList.getJSONObject(i);
                    if (recordObj.getString("orderType").equals("2") && recordObj.getString("status").equals("1") && Float.valueOf(MoneyUtil.fenToYuan(orderInfo.getMoney() + "")).equals(recordObj.getFloatValue("consumeFee"))) {
                        if (orderInfo.getPay3rdOrderNo().equals(recordObj.getString("orderNumber"))) {//成功订单
                            logger.info("SYB订单查询.." + recordObj);
                            MsgPayResult msgPayResult = new MsgPayResult();
                            msgPayResult.setChannel(orderInfo.getChannel());
                            msgPayResult.setTradeNo(orderInfo.getId().toString());
                            msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                            msgPayResult.setOrderId(recordObj.getString("orderNumber"));
                            msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                            msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                            msgPayResult.setBillTime(timeStamp2Date(recordObj.getString("updateTime")));

                            msgPayResult.setChannelPayMsgResult(JSONObject.toJSONString(recordObj));
                            chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                            chargeService.notifyUserPaySucc(orderInfo.getId());

                            logger.info("syb订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney());
                            break;
                        }
                    }
                }
            } else {
                logger.info("收银呗订单查询.." + resultObj);
                String accountJson = userRecipientInfo.getAccountJson();
                JSONObject accountObj = JSONObject.parseObject(accountJson);
                String passport = userRecipientInfo.getChannelAccount().split("_")[0];

                cookieObj = new JSONObject();
                url = "https://www.shouyinbei.net/api/userInfo/" + passport + "/" + accountObj.getString("password");
                HttpResponse httpResponse_ = HttpUtils.httpFormGet(url, headerMap, "", "syb用户查询");
                resultObj = JSONObject.parseObject(httpResponse_.getDocument().body().text());
                logger.info("syb登录" + resultObj);
                if (resultObj.getIntValue("code") != 200) {
                    break;
                }
                JSONObject data = resultObj.getJSONObject("data");
                JSONObject userApp = data.getJSONObject("userApp");
                userId = userApp.getString("userId");
                cookieObj.put("userId", userId);
                merchantCode = userApp.getString("merchantCode");
                cookieObj.put("merchantCode", merchantCode);
                token = userApp.getString("token");
                cookieObj.put("token", token);
                logger.info("syb登录token：" + token);

                url = "https://www.shouyinbei.net/api/merchantBaseInfo/manageMerchantManageList";
                headerMap = new HashMap<>();
                headerMap.put("myLoginName", passport);
                headerMap.put("token", token);
                headerMap.put("User-Agent", "shou yin bei/2.2.3 (iPhone; iOS 15.4.1; Scale/3.00)");
                JSONObject bussinfo = new JSONObject();
                bussinfo.put("userId", userId);


                String bussRes = HttpUtils.sendJsonMessage(url, headerMap, bussinfo.toJSONString());
                JSONObject bussResObj = JSONObject.parseObject(bussRes);
                if (bussResObj.getIntValue("code") == 200) {
                    JSONArray merList = bussResObj.getJSONObject("data").getJSONArray("merchantBaseInfoList");
                    String queryLoginName = "";
                    String queryToken = "";
                    for (int i = 0; i < merList.size(); i++) {
                        JSONObject merObj = merList.getJSONObject(i);
                        if (!merObj.getString("merchantAuditStatus").equalsIgnoreCase("3")) {
                            continue;
                        }
                        userId = merObj.getString("userId");
                        cookieObj.put("userId", userId);
                        merchantCode = merObj.getString("merchantCode");
                        cookieObj.put("merchantCode", merchantCode);
                        String loginName = merObj.getString("loginName");
                        cookieObj.put("loginName", loginName);
                        TRecipientInfo query = new TRecipientInfo();
                        query.setChannelAccount(passport + "_" + merObj.getString("alias"));
                        query.setChannel("alipay_syb_h5");
                        List<TRecipientInfo> userRecipientInfoList = userRecipientService.selectTRecipientInfoList(query);

                        if (userRecipientInfoList.size() == 0) {

                            if (i == 0) {
                                queryLoginName = loginName;
                                queryToken = token;
                                userRecipientInfo.setChannelAccount(passport + "_" + merObj.getString("alias"));
//                                userRecipientInfo.setReceiptQrcode(snListObj.getString("terminal_number"));
                                userRecipientInfo.setOnline(1);
                                userRecipientInfo.setCookie(cookieObj.toJSONString());
                                userRecipientService.updateTRecipientInfo(userRecipientInfo);
                            } else {
                                url = "https://www.shouyinbei.net/api/userInfo/";
                                logger.info("新增登录携带的loginName：" + queryLoginName + "   token：" + queryToken);
                                headerMap = new HashMap<>();
                                headerMap.put("myLoginName", queryLoginName);
                                headerMap.put("token", queryToken);
                                String password = merObj.getString("password");
                                cookieObj.put("loginName", loginName);
                                url = "https://www.shouyinbei.net/api/userInfo/" + loginName + "/" + password;
                                httpResponse_ = HttpUtils.httpFormGet(url, headerMap, "", "");
                                resultObj = JSONObject.parseObject(httpResponse_.getDocument().body().text());
                                if (resultObj.getIntValue("code") != 200) {
                                    break;
                                }
                                data = resultObj.getJSONObject("data");
                                userApp = data.getJSONObject("userApp");
                                userId = userApp.getString("userId");
                                cookieObj.put("userId", userId);
                                merchantCode = userApp.getString("merchantCode");
                                cookieObj.put("merchantCode", merchantCode);
                                String newtoken = userApp.getString("token");
                                cookieObj.put("token", newtoken);
                                queryLoginName = loginName;
                                queryToken = token;
                                TRecipientInfo newUserRecipientInfo = new TRecipientInfo();
                                BeanUtils.copyProperties(userRecipientInfo, newUserRecipientInfo);
                                newUserRecipientInfo.setId(null);
                                newUserRecipientInfo.setChannelAccount(passport + "_" + merObj.getString("alias"));
//                                userRecipientInfo.setReceiptQrcode(snListObj.getJSONObject("data").getString("terminal_number"));
                                newUserRecipientInfo.setOnline(1);
                                newUserRecipientInfo.setCookie(cookieObj.toJSONString());
                                userRecipientService.insertTRecipientInfo(newUserRecipientInfo);
                            }
                        } else {
                            if (passport.equalsIgnoreCase(merObj.getString("loginName"))) {
                                queryLoginName = loginName;
                                queryToken = token;
                                TRecipientInfo userRecipientInfo1 = userRecipientInfoList.get(0);
                                userRecipientInfo1.setOnline(1);
                                userRecipientInfo1.setCookie(cookieObj.toJSONString());
                                userRecipientService.updateTRecipientInfo(userRecipientInfo1);
                                continue;
                            }
                            logger.info("修改登录携带的loginName：" + queryLoginName + "   token：" + queryToken);
                            url = "https://www.shouyinbei.net/api/userInfo/";
                            headerMap = new HashMap<>();
                            headerMap.put("myLoginName", queryLoginName);
                            headerMap.put("token", queryToken);
                            String password = merObj.getString("password");
                            cookieObj.put("loginName", loginName);
                            url = "https://www.shouyinbei.net/api/userInfo/" + loginName + "/" + password;
                            httpResponse_ = HttpUtils.httpFormGet(url, headerMap, "", "");
                            resultObj = JSONObject.parseObject(httpResponse_.getDocument().body().text());
                            if (resultObj.getIntValue("code") != 200) {
                                break;
                            }
                            data = resultObj.getJSONObject("data");
                            userApp = data.getJSONObject("userApp");
                            userId = userApp.getString("userId");
                            cookieObj.put("userId", userId);
                            merchantCode = userApp.getString("merchantCode");
                            cookieObj.put("merchantCode", merchantCode);
                            String newtoken = userApp.getString("token");
                            cookieObj.put("token", newtoken);
                            queryLoginName = loginName;
                            queryToken = newtoken;
                            logger.info("二次syb登录token：" + newtoken);
                            TRecipientInfo userRecipientInfo1 = userRecipientInfoList.get(0);
                            userRecipientInfo1.setOnline(1);
                            userRecipientInfo1.setCookie(cookieObj.toJSONString());
                            userRecipientService.updateTRecipientInfo(userRecipientInfo1);

                        }
                    }
                }
            }
        }
    }

    private String timeStamp2Date(String str_num) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的时间格式
        if (str_num.length() == 13) {
            String date = sdf.format(new Date(Long.parseLong(str_num)));
            return date;
        } else {
            String date = sdf.format(new Date(Integer.parseInt(str_num) * 1000L));
            return date;
        }
    }


}
